#include "database.h"


CDatabase::CDatabase():	Database(0) 
{
	QueryHandle[0] = NULL;
	QueryHandle[1] = NULL;
}


CDatabase::~CDatabase()
{
	
	if(Database)
		sqlite3_close(Database);
}


int CDatabase::OpenDatabase(const char *TFilename) 
{
	
	int Result = sqlite3_open_v2(TFilename, &Database, SQLITE_OPEN_READWRITE, NULL);
	if(Result != SQLITE_OK) 
	{
		printf("OpenDatabase: %s\n", sqlite3_errmsg(Database));
		sqlite3_close(Database);
		return 0;
	}
	return 1;
}


int CDatabase::CreateDatabase(const char *TFilename) 
{
	
	int Result = sqlite3_open_v2(TFilename, &Database, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
	if(Result != SQLITE_OK) 
	{
		printf("OpenDatabaseCreate: %s\n", sqlite3_errmsg(Database));
		sqlite3_close(Database);
		return 0;
	}
	return 1;
}


int CDatabase::RunQuery(const char *TQueryString) 
{
	sqlite3_stmt *NewQueryHandle;
	const char *Tail;
	int Result = sqlite3_prepare_v2(Database, TQueryString, strlen(TQueryString), &NewQueryHandle, &Tail);
	if(Result != SQLITE_OK) 
	{
		printf("RunQuery: %s\n", sqlite3_errmsg(Database));
		return 0;
	}

	Result = sqlite3_step(NewQueryHandle);
	if(Result != SQLITE_DONE) 
	{
		printf("RunQuery: %s\n", sqlite3_errmsg(Database));
		return 0;
	}

	Result = sqlite3_finalize(NewQueryHandle);
	if(Result != SQLITE_OK) 
	{
		printf("RunQuery: %s\n", sqlite3_errmsg(Database));
		return 0;
	}
	return 1;
}


int CDatabase::RunDataQuery(const char *TQueryString, int THandle) 
{
	const char *Tail;
	int Result = sqlite3_prepare_v2(Database, TQueryString, strlen(TQueryString), &QueryHandle[THandle], &Tail);
	if(Result != SQLITE_OK) 
	{
		printf("RunDataQuery: %s\n", sqlite3_errmsg(Database));
		return 0;
	}
	return 1;
}


int CDatabase::RunCountQuery(const char *TQueryString) 
{
	RunDataQuery(TQueryString);
	FetchRow();
	int Count = GetInt(0);

	CloseQuery();

	return Count;
}


int CDatabase::FetchRow(int THandle) 
{
	int Result = sqlite3_step(QueryHandle[THandle]);
	switch(Result) 
	{
		case SQLITE_ROW:
			return 1;
		break;
		case SQLITE_DONE:
		break;
		default:
		break;
	}

	return 0;
}


int CDatabase::CloseQuery(int THandle) 
{
	int Result = sqlite3_finalize(QueryHandle[THandle]);
	if(Result != SQLITE_OK) 
	{
		printf("RunQuery: %s\n", sqlite3_errmsg(Database));
		return 0;
	}
	return 1;
}


int CDatabase::GetLastInsertID() 
{
	return sqlite3_last_insert_rowid(Database);
}


int CDatabase::GetInt(int TColumnIndex, int THandle) 
{
	return sqlite3_column_int(QueryHandle[THandle], TColumnIndex);
}


float CDatabase::GetFloat(int TColumnIndex, int THandle) 
{
	return static_cast<float>(sqlite3_column_double(QueryHandle[THandle], TColumnIndex));
}


const char *CDatabase::GetString(int TColumnIndex, int THandle) 
{
	return (const char *)sqlite3_column_text(QueryHandle[THandle], TColumnIndex);
}
